#include <stdio.h>

#include "common.h"
#include "mediaparser.h"

namespace MParser {

mediaparser::mediaparser(const char *filename):
    m_nStreamNum (0),
    fmt_ctx      (NULL),
    format_opts  (NULL)
{
    this->filename = filename;

//    printf("Hello, world, avformat versoin: %u\n", avformat_version());
//    printf("ffmpeg libavformat license: %s\n", avformat_license());
}

int mediaparser::open()
{
    int err;
    AVInputFormat     *iformat = NULL;

    if (!filename) return -1;

    av_register_all();

    if ((err = avformat_open_input(&fmt_ctx,
                                   filename, iformat,
                                   &format_opts)) < 0) {
        fprintf(stderr, "failed to open : %s,err:%d\n", filename, err);
        return -1;
    }

    return 0;
}

int mediaparser::parse()
{
    int ret = -1, err = 0;
    AVDictionaryEntry *t       = NULL;

    if ((t = av_dict_get(format_opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
        av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);
        goto func_exit;
    }

    if ((err = avformat_find_stream_info(fmt_ctx, NULL)) < 0) {
        fprintf(stderr, "failed to find stream info\n");
        goto func_exit;
    }

//    av_dump_format(fmt_ctx, 0, filename, 0);

    ret = 0;

func_exit:
    return ret;
}

int mediaparser::getDuration()
{
    if (fmt_ctx)
       return fmt_ctx->duration/AV_TIME_BASE;

	return 0;
}
    
const char* mediaparser::getFormat()
{
    if (fmt_ctx &&  fmt_ctx->iformat->name)   
        return fmt_ctx->iformat->name;

    return NULL;
}

int mediaparser::getStreamsInfo()
{
    if (!fmt_ctx)
        return -1;
   
    m_nStreamNum = fmt_ctx->nb_streams;

    printf("\t %d streams found:\n", m_nStreamNum);

    for (int n = 0; n < m_nStreamNum; n++) {
        AVStream *st = fmt_ctx->streams[n];
        switch (st->codec->codec_type) {
            case AVMEDIA_TYPE_VIDEO:
                printf("\tVideo  Stream#%d: %s\n", n, avcodec_get_name(st->codec->codec_id));
                break;
            case AVMEDIA_TYPE_AUDIO: 
                printf("\tAudio  Stream#%d: %s\n", n, avcodec_get_name(st->codec->codec_id));
                break;
            case AVMEDIA_TYPE_SUBTITLE: 
                printf("\tSubtitle  Stream#%d: %s\n", n, avcodec_get_name(st->codec->codec_id));
                break;
            default:
                 printf("\tUnknow stream type\n", n, avcodec_get_name(st->codec->codec_id));
        }     
    } 
   
    return -1;
}

const char* mediaparser::getAudioCodec()
{
    return NULL;
}

int mediaparser::close()
{
    if (fmt_ctx)
        av_close_input_file(fmt_ctx);
    fmt_ctx  = NULL;    
}

mediaparser::~mediaparser()
{
    filename    = NULL;
    format_opts = NULL;
}

};
